package main

import (
	// "bvnet"
	"code.google.com/p/go.net/websocket"
	. "controllers"
	"flag"
	. "golanger.com/middleware"
	"helper"
	"jk/jklog"
	. "jk/jkserver"
	"net/http"
	"os"
	"path/filepath"
	"runtime"
	_ "templateFunc"
)

var (
	addr          = flag.String("addr", ":80", "Server port")
	configPath    = flag.String("config", "./config", "site filepath of config")
	ownConfigPath = flag.String("jkconfig", "./jkconfig", "own config")
)

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU() - 1)

	flag.Parse()
	os.Chdir(filepath.Dir(os.Args[0]))

	jklog.L().Noneln("Listen server address: " + *addr)
	jklog.L().Noneln("Read configuration file success, filepath: " + filepath.Join(filepath.Dir(os.Args[0]), *configPath))

	App.Load(*configPath)

	// read own config
	jklog.L().Noneln("Read Own Config: " + *ownConfigPath)
	helper.OpenConfig(*ownConfigPath)
	jklog.L().SetLevel(helper.LogLevel())

	if mongoDns, ok := App.Database["MongoDB"]; ok && mongoDns != "" {
		mgoServer := helper.NewMongo(mongoDns)
		defer mgoServer.Close()
		Middleware.Add("db", mgoServer)
	}
	if mongoDns, ok := App.Database["MongoDBGlobal"]; ok && mongoDns != "" {
		mgoServer := helper.NewMongo(mongoDns)
		defer mgoServer.Close()
		Middleware.Add("dbglobal", mgoServer)
	}

	http.Handle("/chat", websocket.Handler(UserConnection))
	//go UserConnection(websocket.Conn)

	// start jkserver
	JK_StartServer()

	// bvnet.JKStartBroadCast()
	App.AddHeader("Content-Type", "text/html; charset=utf-8")
	App.ListenAndServe(*addr, App)
}
